package com.fs.controller.admin;



import com.fs.constant.JwtClaimsConstant;
import com.fs.dto.EmployeeDTO;
import com.fs.dto.EmployeeLoginDTO;
import com.fs.dto.EmployeePageQueryDTO;
import com.fs.dto.EmployeeRegisterDTO;
import com.fs.entity.Employee;
import com.fs.properties.JwtProperties;
import com.fs.result.PageResult;
import com.fs.result.Result;
import com.fs.service.EmployeeService;
import com.fs.utils.JwtUtil;
import com.fs.vo.EmployeeLoginVO;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/admin/employee")
@Slf4j
@Api(tags = "员工相关接口")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private JwtProperties jwtProperties;


    /*员工注册*/
    @PostMapping("/register")
    @ApiOperation("注册员工")
    public Result register(@RequestBody EmployeeRegisterDTO employeeRegisterDTO) {
        log.info("注册员工：{}", employeeRegisterDTO);
        String save = employeeService.save(employeeRegisterDTO);
        return Result.success(save);
    }

    /*员工登录*/
    @PostMapping("/login")
    @ApiOperation("员工登录")
    public Result<EmployeeLoginVO> login(@RequestBody EmployeeLoginDTO employeeLoginDTO) {
        log.info("员工登录：{}", employeeLoginDTO);

        Employee employee = employeeService.login(employeeLoginDTO);

        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.EMP_ID, employee.getId());
        String token = JwtUtil.createJWT(
                jwtProperties.getAdminSecretKey(),
                jwtProperties.getAdminTtl(),
                claims);

        EmployeeLoginVO employeeLoginVO = EmployeeLoginVO.builder()
                .id(employee.getId())
                .username(employee.getUsername())
                .name(employee.getName())
                .token(token)
                .build();

        return Result.success(employeeLoginVO);
    }

    /*退出登录*/
    @PostMapping("/logout")
    @ApiOperation("退出登录")
    public Result<String> logout(){
        return Result.success();
    }


    /* 根据ID查询员工信息 */
    @GetMapping("/view")
    @ApiOperation("根据ID查询员工信息")
    public Result<Employee> getById(HttpServletRequest request) {
        //从token中获取userid
        Long userId = TokenUserId(request);
        log.info("员工id：{}",userId);
        Employee employee = employeeService.getById(userId);
        return Result.success(employee);
    }

    /*编辑员工信息*/
    @PutMapping
    @ApiOperation("编辑员工信息")
    public Result update(@RequestBody EmployeeDTO employeeDTO) {
        log.info("编辑员工信息:{} {}",employeeDTO.getId(), employeeDTO);
        String message = employeeService.update(employeeDTO);
        return Result.success(message);
    }

    /*删除员工*/
    @DeleteMapping("/{ids}")
    @ApiOperation("删除员工")
    public Result deleteEmployee(@PathVariable List<Long> ids) {
        log.info("删除员工的id：{}",ids);
        String msg = employeeService.deleteByIds(ids);
        return Result.success(msg);
    }

    /* 分页查询 */
    @GetMapping("/page")
    @ApiOperation("员工分页查询")
    public Result<PageResult> pageby(EmployeePageQueryDTO employeePageQueryDTO) {
        log.info("员工分页查询：{}", employeePageQueryDTO);
        PageResult pageResult = employeeService.pageQuery(employeePageQueryDTO);
        return Result.success(pageResult);
    }

    /* 启用禁用员工账号 */
    @PostMapping("/status/{status}")
    @ApiOperation("启用禁用员工账号")
    public Result startOrStop(@PathVariable Integer status,Long id){
        log.info("启用禁用员工账号：{}，{}",status,id);
        employeeService.startOrStop(status,id);
        return Result.success();
    }

    //获取token中的userid
    private Long TokenUserId(HttpServletRequest request){
        String token = request.getHeader("Authorization");
        if (token == null || token.isEmpty()) {
            token = request.getHeader("token"); // 兼容 Swagger
        }

        if (token.startsWith("Bearer ")) {
            token = token.substring(7);
        }
        // 解密 token
        String secretKey = jwtProperties.getAdminSecretKey();
        Claims claims = JwtUtil.parseJWT(secretKey, token);
        // ⚠️ 注意这里改成 userId（与生成端一致）
        Object userIdObj = claims.get(JwtClaimsConstant.USER_ID);
        Long userId = Long.valueOf(userIdObj.toString());
        return userId;
    }
}
